from datetime import datetime
import random
import re
from flask import current_app, jsonify
from flask import make_response
from flask import request,json
from flask import session

from info import constants, db
from info import redis_store
from info.constants import IMAGE_CODE_REDIS_EXPIRES
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue

# ******************退出登陆*****************
@passport_blue.route("/logout",methods = ["POST"])
def logout():
    # 清楚session
    session.pop("user_id",None)
    session.pop("nick_name",None)
    session.pop("is_admin", None)
    session.pop("mobile",None)
    # 返回响应
    return jsonify(errno = RET.OK,errmsg = "退出成功")
# ********************登陸用戶************
@passport_blue.route("/login", methods = ["POST"])
def login():
# 获取请求参数
    moblie = request.json.get("mobile")
    password = request.json.get("password")
# 校验参数，为空校验
    if not all([moblie, password]):
        return jsonify(errno = RET.PARAMERR, errmsg = "参数不全")
# 根据用户手机号取出用户对象
    try:
        user = User.query.filter(User.mobile == moblie).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "获取用户失败")
    # 判断用户是否存在
    if not user:
        return jsonify(errno = RET.NODATA, errmsg = "该用户是否存在")
    # 校验密码是否正确
    # if user.password_hash != password:
    if not user.check_password(password):
        return jsonify(errno = RET.DATAERR, errmsg = "密码错误")
    # 记录用户登录信息到session
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 记录用户最后一次登陆时间
    user.last_login = datetime.now()
    # try:
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
# 返回响应
    return jsonify(errno = RET.OK,errmsg = "登陆成功")
# *************注册用户***************
@passport_blue.route("/register",methods = ["POST"])
def register():
    # 请求获取参数（手机号，短信验证码，密码）
    dict_data = request.get_json()  # 等价于requset.json
    mobile = dict_data.get("mobile")
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")
    # 校验参数 为空校验
    if not all([mobile,sms_code,password]):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数不全")
    # 通过手机号作为key取出redis中的短信验证码
    try:
        redis_sms_code = redis_store.get("sms_code:%s"%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "短信验证码获取失败")
    # 判断短信验证码是否过期
    if not redis_sms_code:
        return jsonify(errno = RET.NODATA, errmsg = "短信验证码已过期")
    # 删除redis中的短信验证码
    try:
        redis_store.delete("sms_code:%s"%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.NODATA,errmsg = "短信验证码删除异常")
    # 判断redis中的短信验证码和传入进来的短信验证码是否相等
    if redis_sms_code != sms_code:
        return jsonify(errno = RET.DATAERR, errmsg="短信验证码填写错误")
    # 创建用户对象，设置属性
    user = User()
    user.nick_name = mobile
    # user.password_hash = password  # 未加密
    user.password = password  # 已加密
    user.mobile = mobile
    user.signature = "你应该是一场梦，我应该是一阵风"
    # 保存到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR, errmsg = "注册用户失败")
    # 返回响应
    return jsonify(errno = RET.OK,errmsg = "注册成功")
# *************发送短信验证吗*************
@passport_blue.route("/sms_code",methods = ["POST"])
def sms_code():
    # 获取请求参数
    json_data = request.data
    dict_data = json.loads(json_data)
    moblie = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")
    # 校验参数为空校验
    if not all([moblie,image_code,image_code_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数不完整")
    # 校验手机号格式
    if not re.match("1[356789]\\d{9}",moblie):
        return jsonify(errno = RET.DATAERR,errmsg = "手机号错误")
    # 通过图片验证码编号，取出redis中的图片验证码A
    try:
        redis_image_code = redis_store.get("image_code:%s"%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "图形验证码获取失败")
    # 判断图片验证码A是否过期
    if not redis_image_code:
        return jsonify(errno = RET.NODATA,errmsg = "图片验证码已过期")
    # 删除图片验证码A
    try:
        redis_store.delete("image_code:%s"%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "删除图片验证码失败")
    # 判读请求参数中的验证码B,和redis中的验证码A相等
    if image_code != redis_image_code:
        return jsonify(errno = RET.DATAERR,errmsg = "图片验证码填写错误")
    # 生成短信验证码（随机数）
    sms_code = "%06d"%random.randint(0,999999)
    current_app.logger.debug("短信验证码是 = %s"%sms_code)
    # 9.调用ccp模块发送短信
    # try:
    #     ccp = CCP()
    #     result = ccp.send_template_sms(moblie,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60],1)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno = RET.THIRDERR,errmsg = "云通信异常")
# 判断短信是否发送成功
#     if result == -1:
#         return jsonify(errno = RET.DATAERR,errmsg = "短信发送失败")
    # 保存短信验证码到redis
    try:
        redis_store.set("sms_code:%s"%moblie,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "短信验证码保存失败")
# 返回响应
    return jsonify(errno = RET.OK,errmsg = "发送成功")
# **************获取图片验证码****************
@passport_blue.route("/image_code")
def image_code():
    # 获取参数校验参数
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    if not cur_id:
        return "图片验证码编号不全"
    # 生成图片验证码
    name,text,image_data = captcha.generate_captcha()
    # 保存图片验证码到redis中 key values max_age
    try:
        redis_store.set("image_code:%s"%cur_id,text,IMAGE_CODE_REDIS_EXPIRES)
    # 判断是否有上个验证码编号，如果有 删除
        if pre_id:
            redis_store.delete("image_code:%s"%pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return "验证码保存失败"
    # 返回验证码
    response = make_response(image_data)
    response.headers["Content-Type"] = "image/png"
    return response